/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import dao.MyQuery;
import dao.UserDAO;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.simple.JSONArray;
import pojo.User;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/**
 *
 * @author TrieuKhang
 */
@WebServlet(name = "ajax_login", urlPatterns = {"/ajax_login"})
public class ajax_login extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        PrintWriter out = response.getWriter();

        try {
            /*
             * TODO output your page here. You may use following sample code.
             */
            JSONParser jP = new JSONParser();
            JSONObject jO = new JSONObject();

            try {
                jO = (JSONObject) jP.parse(request.getParameter("data"));
                //out.println("false");
            } catch (ParseException ex) {
                //Logger.getLogger(ajax_login.class.getName()).log(Level.SEVERE, null, ex);
                out.println(ex.toString());
                //return;
            }        

            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/x-json; charset=UTF-8");    
            
            String username = (String) jO.get("username");
            
            String pass = (String) jO.get("password");                 
            
            User user = new User();
            
            user.setUsername(username);
            user.setPassword(pass);                        
            
            boolean result = false;
            
            HttpSession session = request.getSession();                            
            
            String redirectUrl = "";     
            
            result = UserDAO.login(user);
            
            if(result){
                
                session.setAttribute("isLogin", true);
                session.setAttribute("currentUser", UserDAO.getLoginUser(user));
                
                //redirect        
                redirectUrl = "index.jsp";
            }
            
            //init JSON
            JSONObject new_jo = new JSONObject();
            
            new_jo.put("result", result);
            new_jo.put("user", user.getUsername());
            new_jo.put("url", redirectUrl);            
            
            //new_jo.put("abc", username);
            
            out.println(new_jo);
            //neu ko co thi in ra false
            //out.println("false");
        }catch( Exception e){
            out.println("lỗi " + e.toString());
        }finally {   
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void splitat(char c) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
